class Solution {
public:
    int tmpNums[500010];
    int tmpIndex[500010];
    vector<int> ret;
    vector<int> index;
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        ret.resize(n);
        index.resize(n);
        // 构建映射
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }
        MergeSort(nums, 0, n - 1);
        return ret;
    }

    void MergeSort(vector<int>& nums,int begin,int end)
    {
        if(begin>=end)return;

        int mid=(begin+end)/2;
        MergeSort(nums,begin,mid);
        MergeSort(nums,mid+1,end);

        int begin1=begin,end1=mid;
        int begin2=mid+1,end2=end;
        int j=0;
        while(begin1<=end1&&begin2<=end2)
        {
            if(nums[begin1]<=nums[begin2])
            {
                tmpNums[j]=nums[begin2];
                tmpIndex[j++]=index[begin2++];
            }
            else
            {
                ret[index[begin1]]+=(end2-begin2+1);
                tmpNums[j]=nums[begin1];
                tmpIndex[j++]=index[begin1++];
            }
        }

        while(begin1<=end1)
        {
            tmpNums[j]=nums[begin1];
            tmpIndex[j++]=index[begin1++];
        }

        while(begin2<=end2)
        {
            tmpNums[j]=nums[begin2];
            tmpIndex[j++]=index[begin2++];
        }
        for (int i = begin; i <= end; i++) {
            nums[i] = tmpNums[i - begin];
            index[i] = tmpIndex[i - begin];
        }
    }
};